package com.xm.xmapp;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xm.xmapp.base.BaseActivity;

public class ShowURLActivity extends BaseActivity implements OnClickListener {

	private String url;
	private WebView webView;
	private ImageView back;
	private TextView title;
	/**
	 * 是否需要重写返回按钮事件
	 */
	private boolean go_back_wab;
	private ProgressBar pb_progressbar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_showurl);
	}

	@Override
	public void initView() {

		webView = (WebView) findViewById(R.id.wb_webView);
		back = (ImageView) findViewById(R.id.back);
		title = (TextView) findViewById(R.id.title);
		pb_progressbar = (ProgressBar) findViewById(R.id.pb_progressbar);
	}

	@SuppressWarnings("deprecation")
	@Override
	public void initData() {

		url = getIntent().getStringExtra("url");
		title.setText("" + getIntent().getStringExtra("title"));
		go_back_wab = getIntent().getBooleanExtra("go_back_wab", false);

		webView.loadUrl(url);
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

		// 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				//
				// 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
				if (url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
					startActivity(intent);
					view.reload();
					return true;
				}
				view.loadUrl(url);
				return true;
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				
				if (newProgress == 100) {
					pb_progressbar.setVisibility(View.GONE);// 加载完网页进度条消失
				} else {
					pb_progressbar.setVisibility(View.VISIBLE);// 开始加载网页时显示进度条
					pb_progressbar.setProgress(newProgress);// 设置进度值
				}
			}
		});
	}

	@Override
	public void initEvent() {
		back.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.back:
			if (webView.canGoBack() && go_back_wab) {
				webView.goBack();
			} else {
				finish();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack() && go_back_wab) {
			webView.goBack();
			return true;
		} else {
			finish();
		}
		return true;
	}

}
